package com.rtx.api.utils;

import com.rtx.api.annotation.FieldValidate;
import com.rtx.api.enums.FieldValidateType;
import org.springframework.util.Assert;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 字段非空验证工具类
 */
public class FieldValidateUtils {

    /**
     * 验证非空字段
     * @param obj
     */
    public static void fieldNotNull(Object obj,FieldValidateType type) {
        List<Field> fieldList = getFieldList(obj);
        for(Field f : fieldList){
            FieldValidate annotation = f.getAnnotation(FieldValidate.class);
            if(annotation != null){
                if(annotation.type() == FieldValidateType.ALL || annotation.type().getType().contains(type.getType())){
                    f.setAccessible(true);
                    String name = f.getName();
                    Object o = null;
                    try {
                        o = f.get(obj);
                    } catch (IllegalAccessException e) {
                        throw new IllegalArgumentException(e);
                    }
                    if(f.getType() == String.class){
                        Assert.hasText((String) o,name + "不能为空");
                    }else{
                        Assert.notNull(o,name + "不能为空");
                    }
                }
            }
        }
    }

    /**
     * 验证非空字段
     * @param list
     * @param type
     */
    public static void fieldNotNull(List<? extends Object> list,FieldValidateType type) {
        for(Object obj : list){
            fieldNotNull(obj,type);
        }
    }

    /**
     * 获取所有字段
     * @param obj
     * @return
     */
    private static List<Field> getFieldList(Object obj){
        List<Field> fieldList = new ArrayList<>();
        Class<?> c = obj.getClass();
        while(c != null){
            fieldList.addAll(new ArrayList<>(Arrays.asList(c.getDeclaredFields())));
            c = c.getSuperclass();
        }
        return fieldList;
    }
}
